package springboot.test03;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class DataController {

    @Autowired
    private DataService dataService;


    @RequestMapping("/")
    public String getAllRegionStats(HttpServletRequest request, HttpServletResponse response,Model model) throws ServletException, IOException {
        List<CountryModel> countryModels = dataService.getAllRegionStats();
        model.addAttribute("customer",countryModels);
        return "list";
    }

    @RequestMapping(value = "/EcharsShow")
    @ResponseBody
    public List<CountryModel> findById(Model model) {
        List<CountryModel> list = dataService.getAllRegionStats();
        List<CountryModel> list2 = new ArrayList<CountryModel>();
        CountryModel cmodel = new CountryModel();
        int num=0;
        for(int i = 0 ; i < list.size() ; i++) {
            CountryModel countryModel = list.get(i);
            if(i==0){
                cmodel.setCountry(countryModel.getCountry());
                num+=countryModel.getLatestTotalCases();
                continue;
            }
            if(cmodel.getCountry().equals(countryModel.getCountry()))
                num+=countryModel.getLatestTotalCases();
            else {
                CountryModel cmodel2 = new CountryModel();
                cmodel2.setLatestTotalCases(num);
                cmodel2.setCountry(cmodel.getCountry());
                list2.add(cmodel2);
                cmodel.setCountry(countryModel.getCountry());
                num=countryModel.getLatestTotalCases();
            }
        }
        return list2;
    }

    //查询
    @RequestMapping("/query")
    public String Query(String name,Model model){
        List<CountryModel> countryModels = dataService.getAllRegionStats();
        List<CountryModel> list = new ArrayList<CountryModel>();
        for(int i = 0 ; i < countryModels.size() ; i++) {
            if(countryModels.get(i).getCountry().equals(name)||countryModels.get(i).getState().equals(name))
                list.add(countryModels.get(i));
        }
        model.addAttribute("customer",list);

        model.addAttribute("name",name);
        return "list";
    }

}
